"""
    Project defence module.
"""

from datetime import date, timedelta, datetime
from decimal import Decimal
from sqlobject.col import IntCol, ForeignKey, DateCol, TimeCol
from mnemoply.model.model_object import ModelObject
from mnemoply.model.hub import __connection__
from mnemoply.utils import date2str_points

class ProjectDefence(ModelObject):
    """
        Defence of student's ptojects in the end of eduction year.
    """

    model_title = _("Project defence")

    number = IntCol(notNull=True, title=_("Number"))
    group = ForeignKey('Group', notNull=True, title=_("Group"))
    classroom = ForeignKey('Classroom', notNull=True, title=_("Classroom"))
    date = DateCol(notNull=True, default=date.today(), title=_("Date"))
    startTime = TimeCol(notNull=True, title=_("Start time"))
    endTime = TimeCol(notNull=True, default=lambda: datetime.now().time(), title=_("End time"))

    def getNumberStr(self):
        if self.number is None:
            return "-"
        return self.number

    title = property(lambda self: "%s %s %s" % (self.getNumberStr(), self.group.title, date2str_points(self.date)))

    def getDefencePeriod(self):
        """
            Rerurns defence period in hours.
        """

        seconds_in_hour = 2700 # 45 minutes in academic hour
        td = datetime.combine(date.today(), self.endTime) - datetime.combine(date.today(), self.startTime)
        return td.seconds / Decimal(seconds_in_hour)

    def getIndividualDefences(self):
        return list(IndividualProjectDefence.select(
            IndividualProjectDefence.q.defenceID==self.id,
            orderBy=[IndividualProjectDefence.q.startTime]))

    def recalculate(self):
        self.calculateTimetable(self.getIndividualDefences())

    def calculateTimetable(self, id_list):
        duration = 20 # individual defence duration. TODO: move to environment
        date_time = lambda i: (datetime.combine(date.today(), self.startTime) + timedelta(minutes=i * duration))
        for i, d in enumerate(id_list):
            d.startTime = date_time(i).time()

        # Set last individual defence's endTime to defence.endTime
        self.endTime = date_time(len(id_list)).time()

    @classmethod
    def handle_create(cls, kw, post_funcs):
        kw['endTime'] = kw['startTime']

class ProjectDefenceAssistant(ModelObject):
    """
        Teachers which assistante projects defence.
    """

    model_title = _("Project defence assistant")

    defence = ForeignKey('ProjectDefence', notNull=True, title=_("Project defence"))
    assistant = ForeignKey('Person', notNull=True, title=_("Assistant"))

    title = property(lambda self: "%s %s" % (self.defence.title, self.assistant.title))

class IndividualProjectDefence(ModelObject):
    """
        For each student we saved individual defence timetable.
    """

    model_title = _("Individual project defence")

    student = ForeignKey('Student', notNull=True, title=_("Student"))
    defence = ForeignKey('ProjectDefence', notNull=True, title=_("Project defence"))
    startTime = TimeCol(notNull=True, title=_("Start time"))

    title = property(lambda self: "%s %s" % (self.defence.title, self.student.title))
